import datetime
import os

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from config import MYSQL_CONFIG
from model.db import reservoir_sensitivity, TbUsers
from model.db.mapper.model_mapper import weight_refer_is_exist

from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
from model.db import connect


def delete_unused_weight():
    print("weight定时删除任务")
    # 使用 os.listdir() 函数获取文件夹中所有文件名列表
    file_list = os.listdir("./weight")
    # 遍历文件名列表并打印每个文件名
    for file_name in file_list:
        record = weight_refer_is_exist(file_name)
        if record is None:
            try:
                # 使用 os.remove() 函数删除指定文件
                os.remove('./weight/' + file_name)
                print(f"File {file_name} deleted successfully.")
            except FileNotFoundError:
                print(f"File {file_name} not found.")
            except Exception as e:
                print(f"An error occurred: {e}")


def reconnect_database():
    # 获取当前日期和时间
    current_datetime = datetime.datetime.now()
    # 打印当前日期和时间
    print("当前日期和时间：", current_datetime)
    print("定时重连数据库任务，解决长时间不使用，数据库断开连接")
    reservoir_sensitivity.query(TbUsers).all()


class MyScheduler(object):
    _instance = None  # 初始值
    APScheduler = None  # 初始值

    def __new__(cls, *args, **kw):
        if cls._instance is None and cls.APScheduler is None:
            # 第一次初始的时候None ,就做初始化的操作，如果不是第一次就返回第一次生成的对象
            cls._instance = object.__new__(cls, *args, **kw)
            cls.APScheduler = BackgroundScheduler()
            # 以下的 Cron 表达式是设置每天执行任务
            cls.APScheduler.add_job(delete_unused_weight, max_instances=1,
                                    trigger=CronTrigger(hour=17, minute=5, second=00))
            cls.APScheduler.add_job(reconnect_database, 'interval', hours=6)
            # 启动调度器
            cls.APScheduler.start()
        return cls._instance

    def __init__(self):
        pass


# 导出
scheduler = MyScheduler().APScheduler
